package org.thread.test00.demo09;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 打印机
 *
 * @author ZQX
 * @date 2025-03-13
 */
public class Printer {

    /**
     * 打印 - 同步块实现
     *
     * @param user 使用者
     * @param msg  内容
     */
    public void print01(String user, String msg) {
        synchronized (this) {
            System.out.print(user);
            System.out.print(":");
            System.out.println(msg);
        }
    }


    /**
     * 打印 - 同步块实现
     *
     * @param user 使用者
     * @param msg  内容
     */
    private String lock = "";

    public void print02(String user, String msg) {
        synchronized (lock) {
            System.out.print(user);
            System.out.print(":");
            System.out.println(msg);
        }
    }

    /**
     * 打印 - 同步方法实现
     *
     * @param user 使用者
     * @param msg  内容
     */
    public synchronized void print03(String user, String msg) {
        System.out.print(user);
        System.out.print(":");
        System.out.println(msg);
    }

    /**
     * 打印 - 锁对象实现
     *
     * @param user 使用者
     * @param msg  内容
     */
    ReentrantLock reentrantLock = new ReentrantLock();
    public void print04(String user, String msg) {
        try {
            reentrantLock.lock();
            System.out.print(user);
            System.out.print(":");
            System.out.println(msg);
        } finally {
            reentrantLock.unlock();
        }
    }
}
